<script>

// 引入 vue3 的响应式和生命周期方法
import { ref, onMounted } from 'vue'

export default {
    name: "DateUtils",
    // 接收父组件传递的 props（未使用）
    props: ["s"],
    setup() {

        // 当前时间对象，包含时分秒
        const time = ref({
            hour: "",
            minitus: "",
            seconds: ""
        })
        // 当前完整日期字符串
        const nowTime = ref("")
        // 星期数组
        const week = ref([
            "星期天",
            "星期一",
            "星期二",
            "星期三",
            "星期四",
            "星期五",
            "星期六"
        ])


        // 补零函数，将数字补齐到指定位数
        const getIncrease = (num, digit) => {
            let increase = ""
            for (let i = 0; i < digit; i++) {
                increase += "0"
            }
            return (increase + num).slice(-digit)
        }


        // 格式化当前时间和日期
        const timeFormate = () => {
            const newtime = new Date()
            time.value.hour = getIncrease(newtime.getHours(), 2)
            time.value.minitus = getIncrease(newtime.getMinutes(), 2)
            time.value.seconds = getIncrease(newtime.getSeconds(), 2)
            nowTime.value =
                getIncrease(newtime.getFullYear(), 4) +
                "年" +
                getIncrease(newtime.getMonth() + 1, 2) +
                "月" +
                getIncrease(newtime.getDate(), 2) +
                "日 " +
                week.value[newtime.getDay()]
        }


        // 每秒更新时间，递归调用实现时钟效果
        const dateTime = () => {
            timeFormate()
            setTimeout(() => {
                dateTime()
            }, 1000)
        }


        // 组件挂载后启动时钟
        onMounted(() => {
            dateTime()
        })

        return {
            time,
            nowTime,
            week
        }
    }
}
</script>


<template>
    <!-- 日期与时间显示区域 -->
    <div style="padding: 30px;font-size: 30px;">
        <span class="time" id="time">
            今天是：<span class="date">{{ nowTime }}</span>
            <span class="hour" style="margin-left: 5px;">{{ time.hour }}</span>
            <a class="split">:</a>
            <span class="minitus">{{ time.minitus }}</span>
            <a class="split">:</a>
            <span class="seconds">{{ time.seconds }}</span>
        </span>
    </div>
</template>


<style scoped>
.txt-data .time {
    font-size: 1rem;
    margin-right: 0.5rem;
}

.split {
    animation: shark 1s step-end infinite;
    vertical-align: center;
    margin-left: 2px;
    margin-right: 2px;
}

@keyframes shark {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0;
    }
}
</style>
